﻿module Sustainalytics.ControversyAlert.Security {

    export class ControversyAlertPermissionsService implements IControversyAlertPermissionsService {
        constructor(
            private $q: ng.IQService,
            private ClaimsAuthorizationService: Sustainalytics.Claims.ClaimsAuthorizationService) {
        }

        //util function
        public hasValidClaim(resName: string): boolean {
            var ctx = this;

            var params: Sustainalytics.Claims.ResourceParameters[] = new Array();

            var validCA = ctx.ClaimsAuthorizationService.Validate('api/v1/' + resName, 'GET', params);

            return validCA;
        }

        public hasValidClaimPost(resName: string, key: string, value: string): boolean {
            var ctx = this;

            var params: Sustainalytics.Claims.ResourceParameters[] = new Array();
            var resCAParam = new Sustainalytics.Claims.ResourceParameters();

            resCAParam.key = key;
            resCAParam.value = value;
            params.push(resCAParam);

            var validCA = ctx.ClaimsAuthorizationService.Validate('api/v1/' + resName, 'POST', params);

            return validCA;
        }

        //Company/CA claim && at least one of the 3 C claims
        public hasControversyAlert(): boolean {
            var ctx = this;

            var params: Sustainalytics.Claims.ResourceParameters[] = new Array();

            var validControversyAlert = this.hasValidClaim('subscribetoportfolio');

            var atLeastOneCAClaim = this.hasValidClaimPost('subscribetoportfolio', 'alert', 'semimonthly');
            
            return validControversyAlert && atLeastOneCAClaim;
        }
    }

    angular.module(caSecurityModuleName).service('ControversyAlertPermissionsService', ['$q', 'ClaimsAuthorizationService', ControversyAlertPermissionsService]);
}